package com.lzw.bluetoothpractice.Activitys;

import androidx.appcompat.app.AppCompatActivity;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lzw.bluetoothpractice.AppConfig;
import com.lzw.bluetoothpractice.R;
import com.lzw.bluetoothpractice.Utils.AppUtil;
import com.lzw.bluetoothpractice.Utils.SharePreferenceUtils;
import com.lzw.bluetoothpractice.bean.DeviceBean;
import com.lzw.bluetoothpractice.bean.SystemUserBean;
import com.lzw.bluetoothpractice.network.HeadAssmblyUtils;
import com.lzw.bluetoothpractice.network.RetrofitManager;
import com.lzw.bluetoothpractice.network.api.RequestApi;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.lzw.bluetoothpractice.MyApplication.getContext;

public class EquipmentActivity extends BaseActivity {

    private Map<String, String> keyMap;
    private static final String TAG ="ble_tag" ;
    private BluetoothGatt mBluetoothGatt;
    Button floatingActionButton;
    TextView tvBlueName;
    TextView tvBlueMsg;
    BluetoothDevice bluetoothDevice;
    private UUID write_UUID_service;
    private UUID write_UUID_chara;
    private UUID read_UUID_service;
    private UUID read_UUID_chara;
    private UUID notify_UUID_service;
    private UUID notify_UUID_chara;
    private UUID indicate_UUID_service;
    private UUID indicate_UUID_chara;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equipment);
        InitView();
        InitData();

    }

    private void   InitView(){

        InitNavBar2(true,"我的设备",false);
        floatingActionButton=findViewById(R.id.floatingActionButton);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent=new Intent(EquipmentActivity.this, SearchDeviceActivity.class);
                startActivity(intent);
            }
        });
        tvBlueName=findViewById(R.id.tvBlueName);
        tvBlueMsg=findViewById(R.id.tvBlueMsg);

    }

    private void   InitData(){

        try {
            keyMap = HeadAssmblyUtils.HeadAssembly("/dev-api/android/device/selectDeviceByUserId");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String accessToken = SharePreferenceUtils.getString(getContext(),"access_token",null);
        String userid = SharePreferenceUtils.getString(getContext(),"userId",null);;

        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).selectDeviceByUserId(Long.parseLong(userid),"1", AppUtil.getVersionCode() + "", accessToken ,keyMap.get("gmtStr"), keyMap.get("contentMD5"), keyMap.get("hmacCode")).
                observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {

                Log.e("错误",e.getMessage()+"");

            }

            @Override
            public void onNext(JSONObject json) {

                DeviceBean deviceBean = JSON.parseObject(json.toString(), DeviceBean.class);
                if(deviceBean.getCode()==200){


                    tvBlueMsg.setText("设备名称："+deviceBean.getData().getDeviceMac());
                    tvBlueName.setText("设备地址："+deviceBean.getData().getDeviceName());
                    SharePreferenceUtils.putString(getContext(), "DeviceId", deviceBean.getData().getDeviceId()+"");


                }else {
                    Toast toast=Toast.makeText(EquipmentActivity.this,json.get("msg").toString(),Toast.LENGTH_LONG);
                    toast.show();
                }

            }
            private void initServiceAndChara(){
                List<BluetoothGattService> bluetoothGattServices= mBluetoothGatt.getServices();
                for (BluetoothGattService bluetoothGattService:bluetoothGattServices){
                    List<BluetoothGattCharacteristic> characteristics=bluetoothGattService.getCharacteristics();
                    for (BluetoothGattCharacteristic characteristic:characteristics){
                        int charaProp = characteristic.getProperties();
                        if ((charaProp & BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
                            read_UUID_chara=characteristic.getUuid();
                            read_UUID_service=bluetoothGattService.getUuid();
                            Log.e(TAG,"read_chara="+read_UUID_chara+"----read_service="+read_UUID_service);
                        }
                        if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
                            write_UUID_chara=characteristic.getUuid();
                            write_UUID_service=bluetoothGattService.getUuid();
                            Log.e(TAG,"write_chara="+write_UUID_chara+"----write_service="+write_UUID_service);
                        }
                        if ((charaProp & BluetoothGattCharacteristic.PROPERTY_WRITE_NO_RESPONSE) > 0) {
                            write_UUID_chara=characteristic.getUuid();
                            write_UUID_service=bluetoothGattService.getUuid();
                            Log.e(TAG,"write_chara="+write_UUID_chara+"----write_service="+write_UUID_service);

                        }
                        if ((charaProp & BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
                            notify_UUID_chara=characteristic.getUuid();
                            notify_UUID_service=bluetoothGattService.getUuid();
                            Log.e(TAG,"notify_chara="+notify_UUID_chara+"----notify_service="+notify_UUID_service);
                        }
                        if ((charaProp & BluetoothGattCharacteristic.PROPERTY_INDICATE) > 0) {
                            indicate_UUID_chara=characteristic.getUuid();
                            indicate_UUID_service=bluetoothGattService.getUuid();
                            Log.e(TAG,"indicate_chara="+indicate_UUID_chara+"----indicate_service="+indicate_UUID_service);

                        }
                    }
                }
            }


            private void checkPermissions(){
                RxPermissions rxPermissions=new RxPermissions(EquipmentActivity.this);
                rxPermissions.request(Manifest.permission.ACCESS_FINE_LOCATION)
                        .subscribe(new io.reactivex.functions.Consumer<Boolean>(){
                            @Override
                            public void accept(Boolean aBoolean) throws Exception {

                                if (aBoolean) {
                                    // 用户已经同意该权限
                                   // searchBlueTooth();

                                } else {
                                    // 用户拒绝了该权限，并且选中『不再询问』
                                    Toast toast=Toast.makeText(EquipmentActivity.this,"用户开启权限后才能使用",Toast.LENGTH_LONG);
                                }
                            }
                        });

            }
        });
    }
}